/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package integration.BuscaPe;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.MappingJsonFactory;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;

/**
 *
 * @author Abraao
 */
public class ConnectUrlJson {

    private String inputStreamToString(InputStream is) throws IOException {
        if (is != null) {
            Writer writer = new StringWriter();
            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            return writer.toString();
        } else {
            return "";
        }
    }

    public String getJsonFrom(String url) throws MalformedURLException, IOException {
        URL u = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) u.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(15000);
        connection.connect();
        connection.disconnect();
        return inputStreamToString(connection.getInputStream());
    }

    protected List<ProductEntityJson> parserJsonToProduct(String responseJson) throws IOException {
        ArrayList<ProductEntityJson> lista = new ArrayList<ProductEntityJson>();
        JsonFactory f = new MappingJsonFactory();
        JsonParser jp = f.createJsonParser(responseJson);
        ObjectMapper om = new ObjectMapper();
        JsonNode json = om.readTree(jp);
        ArrayNode products = (ArrayNode) json.findValue("product");
        for (JsonNode object : products) {
            ProductEntityJson p = new ProductEntityJson(object);
            lista.add(p);
        }
        return lista;
    }
}
